<template>
  <div class="wrapper login">
    <page-loading :modelValue="pageLoadingModel"></page-loading>
    <div class="login__top"><img class="wrapper__img" src="@/assets/image/logo.png" /></div>
    <div class="login__ct">
      <div class="app__title">随你运货主版1.0</div>
      <div class="wrapper__input">
        <input class="wrapper__input__content" placeholder="请输入货主账号" type="text" v-model="formModel.account" />
        <div class="from-error" v-show="accountErrorMsg !== ''">{{ accountErrorMsg }}</div>
      </div>
      <div class="wrapper__input wrapper__input__password">
        <input
          class="wrapper__input__content"
          :placeholder="'请输入密码'"
          :type="passwordType"
          v-model="formModel.password"
          autocomplete="new-password"
          @blur="handleInputPassword"
        />
        <div class="iconfont__box" @click="handlePasswordState(!showPasswordState)" v-if="formModel.type === 1">
          <div
            class="iconfont iconfont__password"
            v-if="showPasswordState"
            style="font-size: 20px"
            v-html="'&#xe8c7;'"
          />
          <div class="iconfont iconfont__password" v-html="'&#xe6ce;'" v-else />
        </div>

        <div class="from-error" v-show="passwordErrorMsg !== ''">{{ passwordErrorMsg }}</div>
      </div>
      <div class="btn__box">
        <div class="wrapper__login-button" :class="loginClass" @click="handleLogin">登录</div>
      </div>
      <div class="login__concat">
        <span class="customer" @click="concatCustomer">联系客服</span>
      </div>
      <div class="login__privacy__agreement">
        <img src="@/assets/image/agree.png" @click="useChecked = !useChecked" v-show="useChecked" />
        <img src="@/assets/image/no-agree.png" @click="useChecked = !useChecked" v-show="!useChecked" />
        <p>继续表示您同意</p>
        <span @click="goPage('AgreementPolicy')">《用户服务协议》</span>
        和
        <span @click="goPage('PrivacyAgreement')">《隐私政策》</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent, watchEffect, computed, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import http from '@/http'
import { Toast } from 'vant'
import store from '@/store/index'
import jsBridge from '@/utils/jsBridge'
import Loading from '@/components/PageLoading.vue'
import { NATIVE_TYPE } from '@/type'

type Login = {
  formModel: { userType: 2 } & FromModel
  showPasswordState: boolean
  passwordType: string
  verification: string | number
  mobileReg: any
  accountErrorMsg: string
  passwordErrorMsg: string
  loginTimer: any
  smsTimer: any
  useChecked: boolean
}

type FromModel = {
  account: number | string
  password: string
  [propname: string]: any
}

export default defineComponent({
  name: 'Login',
  components: {
    'page-loading': Loading
  },
  // 只注重主流程的执行，不同业务的函数拆分出去，业务逻辑清晰明了
  setup() {
    // const router = useRouter()
    const data: Login = reactive({
      showPasswordState: false,
      passwordType: 'password',
      formModel: {
        account: '',
        password: '',
        type: 1,
        userType: 2
      },
      mobileReg: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
      verification: '获取验证码',
      accountErrorMsg: '',
      passwordErrorMsg: '',
      loginTimer: null,
      smsTimer: null,
      useChecked: true
    })

    const customerTel = ref<string>('')

    const pageLoadingModel = ref<boolean>(false)

    const _data = toRefs(data)

    const router = useRouter()
    watchEffect(() => {
      const currentRoute = router.currentRoute.value
      const account = currentRoute?.params?.account ?? ''
      if (account) {
        data.formModel.account = account as string
      }
    })

    const loginClass = computed(() => {
      if (data.formModel.account && data.formModel.password) {
        return 'wrapper__can-login-button'
      } else {
        return ''
      }
    })

    // 页面跳转
    const goPage = (name: string): void => {
      console.log(name, 'name')
      router.push({
        name
      })
    }

    // 联系客服
    const concatCustomer = (): void => {
      if (customerTel.value) {
        window.location.href = `tel:${customerTel.value}`
      } else {
        Toast.fail('客服异常 请稍后再试')
      }
    }

    onBeforeMount(async () => {
      const config = store.getters['user/getSystemConfigs']
      if (JSON.stringify(config) === '{}') {
        customerTel.value = await store.dispatch('user/handleInitSystemTel')
      } else {
        customerTel.value = config['tel']
      }
    })

    return {
      ..._data,
      loginClass,
      goPage,
      pageLoadingModel,
      concatCustomer
    }
  },
  methods: {
    /**
     * 修改密码显示状态
     * @param state boolean 状态
     * @return void
     */
    handlePasswordState(state: boolean): void {
      this.showPasswordState = state
      this.passwordType = state === true ? 'text' : 'password'
    },
    /**
     * 实时监听密码框输入信息
     * @param e
     */
    handleInputPassword(e: any): void {
      const value = e.target.value
      if (value && value !== '') {
        this.passwordErrorMsg = ''
      } else {
        this.passwordErrorMsg = '密码不能为空'
      }
    },
    /**
     * 实时监听手机框输入信息
     * @param e
     */
    handleInputAccount(e: any): void {
      const value = e.target.value
      if (value === '') {
        this.accountErrorMsg = '货主账号不能为空'
      } else {
        this.accountErrorMsg = ''
      }
    },
    /**
     * 改变登陆类型
     */
    handleChangeLoginType(): void {
      if (this.formModel.type === 1) {
        this.formModel.type = 2
      } else {
        this.formModel.type = 1
      }
      this.formModel.password = ''
      this.$nextTick(() => {
        if (!this.formModel.type) {
          this.passwordType = 'text'
        } else {
          this.passwordType = 'password'
        }
      })
    },
    /**
     * 立即注册 或 忘记密码
     * @param type 类型
     */
    handleRegisterOrResetClick(type: string): void {
      this.$router.push({ name: 'RegisterOrResetPwd', params: { type } })
    },
    handleLogin() {
      try {
        if (this.loginTimer) {
          clearTimeout(this.loginTimer)
        }
        this.loginTimer = setTimeout(async () => {
          let validataStatus = true
          let msg = ''

          if (!this.formModel.account || this.formModel.account === '') {
            msg = '货主账号不能为空'
            this.accountErrorMsg = msg
            validataStatus = false
            Toast.fail('请确认您的信息是否填写正确')
          } else {
            this.accountErrorMsg = ''
          }
          if (!this.formModel.password || this.formModel.password === '') {
            msg = '密码不能为空'
            this.passwordErrorMsg = msg
            validataStatus = false
            Toast.fail('请确认您的信息是否填写正确')
          } else if (!this.useChecked) {
            Toast.fail('请仔细阅读协议与政策,知晓并同意后请在相应的地方打勾。')
            return
          } else {
            this.passwordErrorMsg = ''
          }

          if (!validataStatus) {
            return
          }
          this.pageLoadingModel = true
          const result = await store.dispatch('user/handleLogin', this.formModel)
          if (result && result.length > 0) {
            const result = await store.dispatch('user/handleGetUserInfo')
            if (result) {
              Toast.success('登录成功')
              localStorage.isLogin = true
              this.$router.push({ name: 'Delivery' })
              jsBridge.jsCallNative(NATIVE_TYPE.LOGIN, { id: result.consignerContact.userId })
            }
          }
          this.pageLoadingModel = false
        }, 300)
      } catch (e: any) {
        Toast.fail(e || '请求失败')
        this.pageLoadingModel = false
      }
    },
    async handleGetSms(): Promise<boolean> {
      try {
        const result = await store.dispatch('user/handleGetSmsCode', {
          account: this.formModel.account,
          type: 2
        })
        if (result) {
          Toast.success('发送成功')
        }
      } catch (e) {
        //
      }
      return true
    }
  },
  beforeUnmount() {
    this.loginTimer && (this.loginTimer = null)
    this.smsTimer && (this.smsTimer = null)
  }
})
</script>

<style lang="scss" scoped>
@import '@/style/variables.scss';
.wrapper {
  width: 100%;
  height: 100%;
  background-color: $color-primary;
  box-sizing: border-box;
  &__img {
    display: block;
    margin: 0 auto 40px;
    width: 66px;
    height: 66px;
  }

  &__input {
    margin: 0 0 24px 0;
    padding: 0;
    background: white;
    border-radius: 6px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    flex-direction: column;
    &__content {
      position: relative;
      border: none;
      height: 58px;
      outline: none;
      padding: 0 16px;
      line-height: 58px;
      box-shadow: 0px 3px 14px 0px #eff7ff;
      -webkit-appearance: none;
      box-shadow: 0px 3px 14px 0px #eff7ff;
      -webkit-box-shadow: 0px 3px 14px 0px #eff7ff;
      width: 100%;
      font-weight: 500;
      background: none;
      font-size: 14px;
      color: $color-text-secondary;
      &::placeholder {
        color: $color-text-secondary;
      }
    }
    &__password {
      position: relative;
      margin-bottom: 10px !important;
      .iconfont__box {
        position: absolute;
        right: 0;
        top: 0;
        width: 22px;
        height: 58px;
        font-size: 20px;
        display: flex;
        align-items: center;
        .iconfont {
          font-size: 18px;
          color: $color-text-regular;
        }
      }
      .validator__box {
        width: 100px;
        font-size: 14px;
        background: rgba(64, 158, 255, 0.1);
        border: 1px solid rgba(64, 158, 255, 0.5);
        color: $color-primary !important;
        font-size: 12px;
        height: 28px;
        text-align: center;
        line-height: 28px;
        border-radius: 15px;
        margin: 15px 10px 0 0;
      }
      .count__down {
        background: rgba(237, 237, 237, 0.1);
        color: $color-text-secondary !important;
        border: 1px solid #ededed;
      }
      .disabled {
        color: $color-text-secondary;
      }
    }
  }
  .btn__box {
    width: 100%;
    display: flex;
    flex: 1;
    background: #ffffff;
    box-shadow: 0px 6px 14px 0px rgba(87, 92, 114, 0.05);
    opacity: 1;
    border-radius: 6px;
    overflow: hidden;
    margin-top: 67px;
    height: 50px;
  }
  &__login-button {
    background: linear-gradient(180deg, #74cdff 0%, #409eff 100%);
    border-radius: 4px;
    color: white;
    font-size: 16px;
    font-weight: 600;
    opacity: 0.5;
    width: 100%;
    text-align: center;
    line-height: 50px;
  }
  &__can-login-button {
    opacity: 1;
  }

  &__login-link {
    font-size: 14px;
    color: $color-primary;
    opacity: 0.5;
  }
}
.login {
  .password__icon {
    width: 22px;
    height: 22px;
  }
  &__top {
    width: 100%;
    height: 207px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    img {
      display: block;
      width: 104px;
      height: 104px;
      position: relative;
      transform: translateY(73px);
    }
  }
  &__ct {
    width: 100%;
    background-color: white;
    height: calc(100% - 207px);
    box-sizing: border-box;
    padding: 40px 35px 34px 35px;
    border-top-left-radius: 66px;
    .app__title {
      font-size: 22px;
      color: $color-text-primary;
      padding: 0 0 35px 0;
      font-weight: 500;
      text-align: center;
    }
  }
  .from-error {
    color: $red;
    font-size: 12px;
    width: 100%;
    margin-top: 5px;
  }
  &__validator__pwd {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    box-sizing: border-box;
    color: #101736;
    .pwd {
      color: #575c72;
    }
  }
  &__privacy__agreement {
    width: 100%;
    padding: 10x 0 0 0;
    font-size: 11px;
    box-sizing: border-box;
    line-height: 10px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    img {
      width: 12px;
      height: 12px;
    }
    span {
      color: $color-primary-light-2;
    }
    p {
      color: $color-text-primary;
      padding-left: 5px;
    }
  }
  &__concat {
    font-size: 14px;
    box-sizing: border-box;
    color: $color-text-regular;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 10px;
    top: 58px;
    color: white;
  }
}
</style>
